//
//  SMSViewController.m
//  MooreDoll
//
//  Created by 郭景豪 on 2014/11/26.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "SMSViewController.h"
#import "WinkAlertView.h"
#import "StartViewController.h"
#import "UserInfoSettingViewController.h"
@interface SMSViewController ()
{
    AFHTTPRequestOperationManager *afManager;
    
    NSTimer *repeatTimer;
    NSInteger timerNumber;
}
@end

@implementation SMSViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //設置控制器title
    self.navigationItem.title=@"驗證碼";
    //設置導航欄左側按鈕
    [self leftBarButton];
    
    
    afManager = [AFHTTPRequestOperationManager manager];
    
    afManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    afManager.responseSerializer.acceptableContentTypes = [afManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];

    
    [self.BT_RepeatSMS setHidden:YES];
    repeatTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(repeatSMS) userInfo:nil repeats:YES];
}

-(void)repeatSMS
{
        //設置一個 數字增加
        timerNumber ++;

        NSString *timerString = NSLocalizedString(@"重寄驗證碼", nil);
        
        NSString *timerStringAddNumber = [NSString stringWithFormat:@"%@(%0.2iS)",timerString,timerNumber];
    self.LB_RepeatSMSButtonTitle.text = timerStringAddNumber;

    [self stopTimer];
}

-(void)stopTimer
{
    //到達 30 歸 0 並且讓 button 可以運作
    if (timerNumber == 30) {
        timerNumber = 0;
        if ([repeatTimer isValid]) {
            [repeatTimer invalidate];
            repeatTimer = nil;
            
            [self.LB_RepeatSMSButtonTitle setHidden:YES];
            [self.BT_RepeatSMS setHidden:NO];
            
        }
    }
}

-(void)leftBarButton
{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [leftButton setImage:[UIImage imageNamed:@"top_back"] forState:UIControlStateNormal];
    [leftButton setFrame:CGRectMake(0, 0, [UIImage imageNamed:@"top_back"].size.width, [UIImage imageNamed:@"top_back"].size.height)];
    [leftButton addTarget:self action:@selector(goBackToSourceVC:)forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBar;
}
//返回
- (void)goBackToSourceVC:(id)sender {

    [[[UIAlertView alloc]initWithTitle:@"中止註冊" message:@"註冊尚未完成，您是否要終止進行中的註冊？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"中止註冊",nil]show];
    
    
}
//縮下鍵盤
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    
    if (self.view == touch.view) {
        [self.view endEditing:YES];
    }
}
- (IBAction)sendPasscode:(id)sender {
    
    self.AV_LoadingAlertView = [[UIAlertView alloc]initWithTitle:@"註冊中" message:@"請等待..." delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    [self.AV_LoadingAlertView show];

    NSDictionary *parameters = @{@"type":@"enable",@"secret":@"openfire",@"countryCode":self.ISO_Country_Code,@"phone":self.userPhoneNumber,@"token":self.token,@"sms":self.TF_SMS.text};
    
    NSLog(@"%@",parameters);

    //發送簡訊 等待回應
    [afManager POST:MD_SERVER_API parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"JSON: %@", responseObject);
        
        NSString *responseResult = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
        //成功
        if ([responseResult isEqualToString:@"0"]) {
            
            //loading 結束
            [self.AV_LoadingAlertView dismissWithClickedButtonIndex:0 animated:NO];
            
            //儲存起來
            [[NSUserDefaults standardUserDefaults]setValue:self.ISO_Country_Code forKey:@"code"];
            
            //使用 userDefaults 去紀錄 帳號密碼
            [[NSUserDefaults standardUserDefaults]setValue:self.userPhoneNumber forKey:@"account"];
            
            [[NSUserDefaults standardUserDefaults]setValue:DEFAULT_PASSWORD forKey:@"password"];

            [[NSUserDefaults standardUserDefaults]synchronize];
            
            //跳到資料設定頁面
            
            UserInfoSettingViewController *userInfoSettingVC = [self.storyboard instantiateViewControllerWithIdentifier:@"UserInfoSettingViewController"];
            
            [userInfoSettingVC.navigationItem setHidesBackButton:YES];
            
            [self.navigationController pushViewController:userInfoSettingVC animated:YES];
            
        }else
        {
            
            [self.AV_LoadingAlertView dismissWithClickedButtonIndex:0 animated:NO];
            
            [WinkAlertView _showAlertViewWithTitle:@"簡訊驗證失敗" content:responseObject[@"msg"] cancelButtonTitle:@"確認" showTime:3.0f];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        
        [self.AV_LoadingAlertView dismissWithClickedButtonIndex:0 animated:NO];
        
        [WinkAlertView _showAlertViewWithTitle:@"失敗" content:@"網路連結失敗" cancelButtonTitle:@"確認" showTime:3.0f];
        
    }];

}

- (IBAction)resendSMS:(id)sender {
    
    [self.LB_RepeatSMSButtonTitle setHidden:NO];
    [self.BT_RepeatSMS setHidden:YES];
    
    repeatTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(repeatSMS) userInfo:nil repeats:YES];

    
    NSDictionary *parameters = @{@"type":@"sms",@"kind":@"1",@"secret":@"openfire",@"countryCode":self.ISO_Country_Code,@"phone":self.userPhoneNumber,@"token":self.token};

    
    NSLog(@"%@",parameters);

    //發送註冊 等待簡訊回應
    [afManager POST:MD_SERVER_API parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"JSON: %@", responseObject);
        
        NSString *responseResult = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
        //成功
        if ([responseResult isEqualToString:@"0"]) {
            
        }else
        {
            [WinkAlertView _showAlertViewWithTitle:@"簡訊重新發送失敗" content:responseObject[@"msg"] cancelButtonTitle:@"確認" showTime:3.0f];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
                
        [WinkAlertView _showAlertViewWithTitle:@"失敗" content:@"網路連結失敗" cancelButtonTitle:@"確認" showTime:3.0f];
        
        
    }];

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1) {
        
//當點選了中止註冊 讓他返回到註冊畫面
        for (UIViewController *collection in self.navigationController.viewControllers) {
            if ([collection isKindOfClass:[LoginOrRegistViewController class]]) {
                [self.navigationController popToViewController:collection animated:YES];
                break;

            }
        }

    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
